package org.luxor.commons.security.component;

import org.luxor.commons.core.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 表单登录失败处理逻辑
 *
 * @author Mr.Yan  @date: 2020/9/18
 */
public class FormAuthenticationFailureHandler implements AuthenticationFailureHandler {
    private static final Logger log = LoggerFactory.getLogger(FormAuthenticationFailureHandler.class);

    /**
     * Called when an authentication attempt fails.
     *
     * @param request   the request during which the authentication attempt occurred.
     * @param response  the response.
     * @param exception the exception which was thrown to reject the authentication
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException {
        log.debug("表单登录失败:{}", exception.getMessage());
        String url = String.format("/login?error=%s", StringUtils.urlEncode(exception.getMessage()));

        response.sendRedirect(url);
    }
}
